const Qs = require('querystring')
const Request = require('../../request')
const { tokenLogger } = require('../util')

const MIRROR_OAUTH_URL = 'https://logintestlf.hwcloudtest.cn/oauth2/v2/token'

/**
 * 镜像环境 code 换取 at
 */
function code2AccessToken({ grant_type, code, client_id, client_secret, redirect_uri }) {
  tokenLogger('info', 'code2AccessToken', `开始换取token: code: ${code}, client_id: ${client_id}, client_secret: ${client_secret}, redirect_uri: ${redirect_uri}`)
  return Request.post(MIRROR_OAUTH_URL, Qs.stringify({
    grant_type: grant_type || 'authorization_code',
    code,
    client_id,
    client_secret,
    redirect_uri
  }, '&', '=', {
    encodeURIComponent: s => s
  }), {
    'Content-Type': 'application/x-www-form-urlencoded'
  }).then(({ data }) => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    return data
  }).catch(err => {
    // handle err
    throw new Error(`code换取token失败: ${err}; Error.response: ${err && err.response && JSON.stringify(err.response.data)}.`)
  })
}

/**
 * 镜像环境使用 rt 刷新 at
 */
function refreshToken({ grant_type, refresh_token, client_id, client_secret }) {
  tokenLogger('info', 'refreshToken', `刷新token: code: ${refresh_token}, client_id: ${client_id}, client_secret: ${client_secret}`)
  return Request.post(MIRROR_OAUTH_URL, Qs.stringify({
    grant_type: grant_type || '',
    refresh_token,
    client_id,
    client_secret
  }), {
    'Content-Type': 'application/x-www-form-urlencoded'
  }).then(({ data }) => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    return data
  }).catch(err => {
    // handle err
    throw new Error(`使用RT刷新token失败: ${err} Error.response: ${err && err.response && JSON.stringify(err.response.data)}. Search string: ${this.searchStr}`)
  })
}

module.exports = { code2AccessToken, refreshToken }
